package com.lin.app.midtermtest.jo6num3;

import java.io.InputStream;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class MyContacts extends ListActivity implements SimpleCursorAdapter.ViewBinder{
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts);
        init();
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {    
		MenuInflater inflater = getMenuInflater();    
	inflater.inflate(R.menu.contactsmenu, menu);    
	return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(id!=-1){
			switch(item.getItemId()){
			case R.id.add:       
				//add       
				addCon();
				return true;    
			case R.id.search: 
				//TODO search   
				searchCon();
				return true;   
			case R.id.modify:      
				//modify     
				modifyCon();
			return true;  
			default:       
				return super.onOptionsItemSelected(item);    
			}
		}else{
			Toast.makeText(this.getApplicationContext(), "Please click a name!", Toast.LENGTH_LONG);
			return super.onOptionsItemSelected(item);
		}
		
		
	}
	
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) { 
		super.onCreateContextMenu(menu, v, menuInfo); 
		MenuInflater inflater = getMenuInflater(); 
		inflater.inflate(R.menu.con_context, menu);
	}
	@Override
	public boolean onContextItemSelected(MenuItem item) {  
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		id = info.id;
		switch (item.getItemId()) {  
		case R.id.cDelete :   
			deleteCon();
			return true;  
		case R.id.cModify:
			modifyCon();
			return true;  
	default:   
		return super.onContextItemSelected(item);  
		}
	}
	
	private void addCon(){
		Intent addNew = new Intent(Intent.ACTION_INSERT,Contacts.CONTENT_URI);
		this.startActivity(addNew);
	}
	private void searchCon(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		/*LayoutInflater inflater = (LayoutInflater) this.getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.search_contact, (ViewGroup)findViewById(R.id.searchRootLayout));*/
		final EditText searchText =  new EditText(this);
		builder.setView(searchText);
		builder.setTitle("Input search key:");
		builder.setPositiveButton("Search", new OnClickListener(){

			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
				String text = searchText.getText().toString();
				
				Intent search = new Intent(Intent.ACTION_SEARCH);
				//search.setType(Contacts.CONTENT_ITEM_TYPE);
				
				search.putExtra(SearchManager.QUERY, text);
				MyContacts.this.startActivity(search);
			}});
		builder.setNegativeButton("Cancel", new OnClickListener(){

			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}});
		
		builder.show();
	}
	
	private void modifyCon(){
		//id = this.getSelectedItemId();
		
		Uri contactPhotoUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,id);
		Intent modify = new Intent(Intent.ACTION_EDIT,contactPhotoUri);
		this.startActivity(modify);
	}
	@SuppressWarnings("deprecation")
	private void deleteCon(){
		//id = this.getSelectedItemId();
		String where = Contacts._ID +" = "+id;
		Log.i("Deleted:",this.getContentResolver().delete(android.provider.Contacts.People.CONTENT_URI, where, null)+"");
		
	}

	public boolean setViewValue(View view, Cursor cursor, int column) {
		// TODO Auto-generated method stub
		
		switch(column){
		case 0:
			Uri contactPhotoUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,cursor.getLong(cursor.getColumnIndex(Contacts._ID)));
			InputStream photoDataStream = Contacts.openContactPhotoInputStream(this.getContentResolver(),contactPhotoUri);
			Bitmap photo = BitmapFactory.decodeStream(photoDataStream);
			if(photo == null ){
				((ImageView) view).setImageResource(R.drawable.ic_contact_picture);
			}else{
				((ImageView) view).setImageBitmap(photo);
			}
			
			break;
		case 1:
			((TextView) view).setText(cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME)));
			break;
		}
		
		return true;
	}
	
	private void init(){
		String[] colums = new String[]{Contacts._ID,Phone.DISPLAY_NAME};
		c = this.getContentResolver().query(
				Contacts.CONTENT_URI, colums, null, null, null);
		this.startManagingCursor(c);
		String[] result = new String[]{Contacts._ID,Phone.DISPLAY_NAME};
		int[] to = new int[]{R.id.ImageView,R.id.TextView};
		
		mAdapter = new SimpleCursorAdapter(this,R.layout.con_row,c,result,to);
		mAdapter.setViewBinder(this);
		this.registerForContextMenu(this.getListView());
		this.setListAdapter(mAdapter);
	}
	@Override
	protected void onListItemClick (ListView l, View v, int position, long id){
		this.id = id;
	}
	
	@Override
	public boolean onKeyDown (int keyCode, KeyEvent event){
		if(keyCode == KeyEvent.KEYCODE_BACK){
			Intent intent = new Intent();
			String name = null;
			Cursor getName = this.getContentResolver().query(Contacts.CONTENT_URI,
					new String[]{Phone.DISPLAY_NAME}, Contacts._ID+" = "+id, null, null);
			if(getName!=null){
				if(getName.moveToFirst()){
					name = getName.getString(getName.getColumnIndex(Phone.DISPLAY_NAME));
					intent.putExtra(LINMidtermTestJo6Num3.MYCON_TAG, name);
					this.setResult(RESULT_OK, intent);
				}else{
					this.setResult(RESULT_CANCELED);
				}
				getName.close();
			}else{
				this.setResult(RESULT_CANCELED);
			}
			
			this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private SimpleCursorAdapter mAdapter ;
	private Cursor c;
	private long id = -1;
	
	
}
